package com.regex.web.controller.essentialinformation;


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.regex.web.utils.QueryResult;
import com.regex.web.entity.essentialinformation.ClCjrjbxxDTO;
import com.regex.web.service.essentialinformation.IClCjrjbxxService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.regex.web.utils.AjaxUtil;
import com.regex.web.utils.Contant;
import com.regex.web.common.excel.ExportExcel;
import com.regex.web.common.excel.ImportExcel;
import com.regex.web.vo.LayTableDataVO;
import com.regex.web.vo.ResultVO;
import com.regex.web.vo.ImportResultVO;


/**
 * <p>
 * 残疾人基本信息 前端控制器
 * </p>
 *
 * @author lyc
 * @since 2021-06-07
 */
@Controller
@RequestMapping("sys/clCjrsbxxcx")
public class ClCjrsbxxcxController {

	private final static Logger logger = LoggerFactory.getLogger(ClCjrsbxxcxController.class);
	
	@Autowired
	private IClCjrjbxxService IClCjrjbxxService;
	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param clCjrjbxxDTO
	 * @return
	 */
	@GetMapping("show")
	public String show() {
		return "sys/clCjrsbxxcx/show";
	}
	
	
	@RequestMapping("getPageData")
	public void getPageData(HttpServletResponse response,
			ClCjrjbxxDTO clCjrjbxxDTO, String limit, String page) {
		LayTableDataVO<ClCjrjbxxDTO> result = new LayTableDataVO<ClCjrjbxxDTO>();
		try {
			
			QueryWrapper<ClCjrjbxxDTO> param = new QueryWrapper<ClCjrjbxxDTO>();
			
			
			if (StringUtils.isNotEmpty(clCjrjbxxDTO.getName())) {
				param.eq("name", clCjrjbxxDTO.getName());
			}
			param.eq("insured_status", "1");
			
			param.orderByDesc("create_time");
			Page<ClCjrjbxxDTO> pageParam = new Page<ClCjrjbxxDTO>();
			if (StringUtils.isEmpty(limit)) {
				limit = Contant.NONMAL_PAGE_SIZE_TEN + "";
			}
			if (StringUtils.isEmpty(page)) {
				page = Contant.NONMAL_PAGE_START + "";
			}
			pageParam.setSize(Integer.parseInt(limit));
			pageParam.setCurrent(Integer.parseInt(page));
			
	        QueryResult<ClCjrjbxxDTO> pageResult = IClCjrjbxxService.page(pageParam, param);
			
			result.setData(pageResult.getDatas());
			result.setCode(0);
			result.setCount(pageResult.getTotalDataCount());
		} catch (Exception e) {
			result.setCode(500);
			AjaxUtil.ajaxJsonSucMessage(response, result);
			e.printStackTrace();
		}
		AjaxUtil.ajaxJsonSucMessage(response, result);
	}
	
	/**
	 * 编辑/新增
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("input")
    public String toSave(@ModelAttribute("id")  String id) {
        return "sys/clCjrjbxx/input";
    }
    
    @GetMapping("get/{id}")
	@ResponseBody
    public ResultVO<ClCjrjbxxDTO> getData(@PathVariable String id) {
	    ClCjrjbxxDTO clCjrjbxxDTO = IClCjrjbxxService.getById(id);
        return ResultVO.success(clCjrjbxxDTO, ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
    /**
	 * 保存
	 * @param clCjrjbxxDTO
	 * @param response
	 */
    @PostMapping("save")
	@ResponseBody
	public ResultVO<String> save(@Valid  @RequestBody ClCjrjbxxDTO clCjrjbxxDTO, HttpServletResponse response) {
		ResultVO<String> result = new ResultVO<String>();
		boolean flag = false;
		if(StringUtils.isNotEmpty(clCjrjbxxDTO.getId())) {
			clCjrjbxxDTO.setUpdateTime(new Date());
			flag = IClCjrjbxxService.updateById(clCjrjbxxDTO);
			if(flag) {
            	return ResultVO.success();
            }
		} else {
			clCjrjbxxDTO.setIsDel(Contant.is_del_undelete);
			clCjrjbxxDTO.setUpdateTime(new Date());
			clCjrjbxxDTO.setCreateTime(new Date());
			flag = IClCjrjbxxService.save(clCjrjbxxDTO);
			if(flag) {
            	return ResultVO.success();
            }
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("detial")
    public String detial(String id, Model model) {
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	ClCjrjbxxDTO clCjrjbxxDTO = IClCjrjbxxService.getById(id);
	            model.addAttribute("clCjrjbxxDTO", clCjrjbxxDTO);
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("detial page is Exception!");
		}
        return "sys/clCjrjbxx/detial";
    }
	
	/**
	 * 删除
	 * @param id
	 * @param response
	 */
	@RequestMapping("del")
    public void del(String id, HttpServletResponse response) {
        int n = 0;
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	boolean flag = IClCjrjbxxService.removeById(id);
	        	if(flag) {
	        		n = 1;
	        	}
	        } else {
	        	n = 2;
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("del page is Exception!");
		}
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    /**
	 * 导出
	 * @param response
	 * @param clCjrjbxxDTO
	 * @return
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(HttpServletResponse response, @ModelAttribute("clCjrjbxxDTO") ClCjrjbxxDTO clCjrjbxxDTO) {
        try {
            QueryWrapper<ClCjrjbxxDTO> param = new QueryWrapper<ClCjrjbxxDTO>();
            param.eq("insured_status", "1");
			param.orderByDesc("create_time");
        	String fileName = "数据"+(new Date()).getTime()+".xlsx";
            
            List<ClCjrjbxxDTO> datas = IClCjrjbxxService.list(param);
            new ExportExcel("数据", ClCjrjbxxDTO.class).setDataList(datas).write(response, fileName).dispose();
            return null; 
        } catch (Exception e) {
        	logger.error("exportFile page is Exception!");
            e.printStackTrace();
        }
        return "redirect:show.htm";
    }
    
    
     /**
     * 
     * 功能描述: <br>
     * 下载导入模板
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "importTemplate")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "残疾人基本信息信息导入模板.xlsx";
            List<ClCjrjbxxDTO> list = new ArrayList<>(); 
            list.add(new ClCjrjbxxDTO());
            new ExportExcel("残疾人基本信息信息数据", ClCjrjbxxDTO.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/sys/clCjrjbxx/show";
    }

    
    /**
     * 
     * 功能描述: <br>
     * 去导入界面
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @GetMapping("toImport")
    public String toImport() {
        return "sys/clCjrjbxx/import_excel";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 导入
     *
     * @param file
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("importFile")
    @ResponseBody
    public ResultVO<ImportResultVO> importFile(MultipartFile file, @RequestParam(required = false, value="param") String param) {
        JSONObject json = JSON.parseObject(param);
        logger.error(json!=null?json.toJSONString():"");
        int successNum=0;
        int failureNum=0;
        StringBuilder failureMsg=new StringBuilder();
        ImportExcel ei;
        List<ClCjrjbxxDTO> list;
        try {
            ei = new ImportExcel(file, 1, 0);
            list=ei.getDataList(ClCjrjbxxDTO.class);
        } catch (Exception e1) {
            e1.printStackTrace();
            list = new ArrayList<>(); 
        }
        for(ClCjrjbxxDTO data : list) {
               data.setUpdateTime(new Date());
               data.setIsDel(Contant.is_del_undelete);
               data.setCreateTime(new Date());
               try {
                   IClCjrjbxxService.saveOrUpdate(data);
                   successNum++;
               } catch (Exception e) {
                   e.printStackTrace();
                   failureNum++;
                   failureMsg.append("数据：").append(JSON.toJSONString(data)).append("导入失败；");
               }
        }
        return ResultVO.success(ImportResultVO.result(successNum, failureNum, failureMsg.toString()), ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
  
	
}
